import { Modal, Input, Form } from 'antd';
import { useEffect, useState, useRef } from 'react';
import { mkdir, updateDir } from '@/services/doc/common'


const DirFormModalInner = ({
    visibleDir,
    onCancel,
    projectId,
    docType,
    onSuccess
}) => {
    const [form] = Form.useForm()
    const [defaultForm, setDefaultForm] = useState();
    const [saveLoading, setSaveLoading] = useState(false)

    const inputRef = useRef(null);

    useEffect(() => {
        // console.log(visibleDir)
        setDefaultForm({
            name: visibleDir.title
        })
    }, [visibleDir])

    useEffect(() => {
        if (defaultForm) {
            // console.log("---resetFields", defaultForm)
            form.resetFields();
        }
        if (inputRef.current) {
            inputRef.current.focus();
        }
    }, [defaultForm])

    const saveDir = async () => {
        const values = await form.validateFields();
        setSaveLoading(true)
        if (visibleDir.id) {
            updateDir(projectId, visibleDir.id, {
                ...values,
            }).then((result) => {
                setSaveLoading(false)
                if (onSuccess) {
                    onSuccess({
                        ...visibleDir,
                        title: values.name
                    })
                }
            })
        } else {
            mkdir(projectId, {
                parentDirId: visibleDir.parentDirId,
                ...values,
                type: docType
            }).then((result) => {
                setSaveLoading(false)
                if (onSuccess) {
                    onSuccess(result?.data)
                }
            })
        }

    }

    return (
        <Modal title={visibleDir.id ? "修改目录" : "新增目录"}
            closable
            onCancel={onCancel}
            confirmLoading={saveLoading}
            onOk={saveDir}
            zIndex={1100}
            visible={!!visibleDir}>
            <Form form={form}
                initialValues={defaultForm}
            >
                <Form.Item
                    label="目录名"
                    name="name"
                    rules={[{
                        required: true,
                        message: '请输入目录名'
                    },
                    {
                        type: "string",
                        max: 20,
                        min: 2,
                        message: '名字为2~20个字符'
                    }]}>
                    <Input ref={inputRef} />
                </Form.Item>
            </Form>
        </Modal>
    )
}

const DirFormModal = (props) => {
    const {
        visibleDir
    } = props;
    if (!visibleDir) {
        return <></>
    }

    return (visibleDir && <DirFormModalInner {...props}></DirFormModalInner>)
}

export default DirFormModal;